package com.dai.code;

import com.dai.common.Node;

/**
 * 反转指定范围的链表
 * @author daijiyong
 */
public class ReverseLinkedList2 {

    public static void main(String[] args) {
        Node head = new Node(1);
        Node temp = head;
        for (int i = 2; i < 10; i++) {
            temp.next = new Node(i);
            temp = temp.next;
        }
        int start = 3;
        int end = 8;
        System.out.println(head + "::反转::" + reverseRangeLinkedList(head, start, end));
    }

    public static Node reverseRangeLinkedList(Node head, int start, int end) {

        if (head == null || head.next == null) {
            return head;
        }

        Node pointer = new Node(-1, head);
        Node pre = pointer;
        Node pointerEnd = pre;
        for (int i = 0; i < start; i++) {
            pointerEnd = pre;
            pre = pre.next;
        }

        head = pre;
        Node cur = pre.next;
        Node next = cur;
        pre.next = null;

        while (next != null && start < end) {
            next = next.next;
            cur.next = pre;
            pre = cur;
            cur = next;
            start++;
        }

        pointerEnd.next = pre;
        head.next = cur;

        return pointer.next;
    }
}
